package com.ming.controller;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ming.domain.Book;
import com.ming.service.BookService;

@RestController
@SpringBootApplication
@RequestMapping("/book")
public class BookController {
    public static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/{id}")
    public Optional<Book> findById(@PathVariable Integer id) {
        return bookService.findOne(id);
    }

    @RequestMapping(value = "/list")
    public List<Book> findAll() {
        return bookService.findAll();
    }

    @RequestMapping(value = "/{id}/{dateStr}")
    public Optional<Book> updatePurchaseDate(@PathVariable Integer id, @PathVariable String dateStr) {
        LocalDate date = LocalDate.parse(dateStr);
        return bookService.updatePurchaseDate(id, date);
    }

    @RequestMapping(value = "/date/{dateStr}")
    public List<Book> findAllByDate(@PathVariable String dateStr) {
        LocalDate date = LocalDate.parse(dateStr);
        if (LocalDate.now().equals(date)) {
            logger.info("dateStr means today");
            return bookService.findAllByDate(LocalDate.now());
        } else {
            return bookService.findAllByDate(date);
        }        
    }
}
